package cn.iluwen.airline.Config.interceptor;

import cn.iluwen.airline.Config.CookieUtil;
import cn.iluwen.airline.Services.AdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;

import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.util.logging.Logger;

/**
 * 管理员认证拦截器
 * 通过Cookie中的adminId进行认证
 */
public class AdminAuthInterceptor implements HandlerInterceptor {
    
    private static final Logger logger = Logger.getLogger(AdminAuthInterceptor.class.getName());
    
    @Autowired
    private AdminService adminService;
    
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        logger.info("AdminAuthInterceptor: 开始验证管理员身份");
        
        // 先通过CookieUtil获取
        String adminId = CookieUtil.getCookieValue(request, "adminId");
        
        // 如果通过工具类没找到，再直接从Cookie中查找
        if (adminId == null) {
            logger.info("通过CookieUtil未找到adminId，尝试直接从Cookie中获取");
            Cookie[] cookies = request.getCookies();
            if (cookies != null) {
                logger.info("请求中包含 " + cookies.length + " 个Cookies");
                for (Cookie cookie : cookies) {
                    logger.info("Cookie: " + cookie.getName() + " = " + cookie.getValue());
                    if ("adminId".equals(cookie.getName())) {
                        adminId = cookie.getValue();
                        logger.info("从Cookie中找到adminId: " + adminId);
                        break;
                    }
                }
            } else {
                logger.info("请求中不包含任何Cookie");
            }
        } else {
            logger.info("通过CookieUtil找到adminId: " + adminId);
        }
        
        // 如果还是没找到，尝试从请求头中查找
        if (adminId == null) {
            logger.info("从Cookie中未找到adminId，尝试从请求头中获取");
            // 先尝试从X-Admin-ID头获取
            adminId = request.getHeader("X-Admin-ID");
            if (adminId != null) {
                logger.info("从请求头X-Admin-ID中找到adminId: " + adminId);
            } else {
                // 再尝试从Authorization头获取
                String authHeader = request.getHeader("Authorization");
                if (authHeader != null && authHeader.startsWith("Bearer ")) {
                    adminId = authHeader.substring(7);
                    logger.info("从Authorization请求头中找到adminId: " + adminId);
                } else {
                    logger.info("请求头中不包含X-Admin-ID或Authorization");
                }
            }
        }
        
        // 验证管理员ID是否有效
        if (adminId != null) {
            if (adminService != null && adminService.getAdminById(adminId) != null) {
                // 将adminId放入请求属性中，便于后续使用
                request.setAttribute("adminId", adminId);
                logger.info("管理员验证成功: " + adminId);
                return true; // 认证通过
            } else if (adminId.startsWith("admin-")) {
                // 简单验证，以支持开发测试
                request.setAttribute("adminId", adminId);
                logger.info("管理员ID格式验证通过: " + adminId);
                return true;
            } else {
                logger.info("管理员ID无效: " + adminId);
            }
        } else {
            logger.info("未找到adminId");
        }
        
        // 认证失败，记录请求信息
        logger.info("认证失败。请求URI: " + request.getRequestURI());
        logger.info("请求方法: " + request.getMethod());
        logger.info("所有请求头: ");
        request.getHeaderNames().asIterator().forEachRemaining(headerName -> 
            logger.info(headerName + ": " + request.getHeader(headerName))
        );
        
        // 返回401错误
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().write("{\"code\":401,\"message\":\"需要管理员权限\",\"data\":null}");
        return false;
    }
}